package com.pure.model
{
	import com.pure.model.vo.UserVO;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class UserProxy extends Proxy
	{
		public static const NAME:String = "UserProxy";
		
		public function UserProxy( )
		{
			super( NAME, new ArrayCollection );
		}
		
		// return data property cast to proper type
		public function get users():ArrayCollection
		{
			return data as ArrayCollection;	// data is declare in Proxy
		}
		
		// add an item to the data	
		public function addItem( item:Object ):void
		{
			users.addItem( item );
		}
		
		// delete an item from the data
		public function deleteItem( item:UserVO ):void
		{
			for(var i:int=0; i<users.length; i++)
			{
				var user:UserVO = users[i] as UserVO;
				if(item.name == user.name)	// update a user
				{
					users.removeItemAt(i);
					return;
				}
			}
		}
		
		// Update or create a user
		public function saveItem( item:UserVO ):void
		{
			var is_exist:Boolean = false;
			for(var i:int=0; i<users.length; i++)
			{
				var user:UserVO = users[i] as UserVO;
				if(item.name == user.name)	// update a user
				{
					user.email = item.email;
					user.school = item.school;
					users[i] = user;
					
					is_exist = true;
				}
			}
			// create a user
			if(!is_exist)
			{
				users.addItem(item);
			}
		}
	}
}